﻿using FPSO.HMI.Utils;
using FPSO.Models.Constant;
using FPSO.Models.Domain;
using FPSO.Models.ViewModel.Controls;
using FPSO.Services;
using FPSO.Services.Impl;
using FPSO.ViewModel.Controls;
using MySql.Data.MySqlClient;
using Opc.Ua;
using OpcUaHelper;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IdentityModel.Protocols.WSTrust;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Xml.Linq;

namespace FPSO.HMI.Views.Dialog
{
    /// <summary>
    /// LoginDialog.xaml 的交互逻辑
    /// </summary>
    public partial class UCAdjValveDialog : Window
    {
        private UCValveViewModel viewModel;
		private List<OPCTag> opcTags = new List<OPCTag>();
		private int current_pv = 0;
		private int set_pv = 0;
        public UCAdjValveDialog(string name,List<OPCTag> tags)
        {
            InitializeComponent();
            viewModel = new UCValveViewModel();
            this.DataContext = viewModel;
            viewModel.ValveName = name;
			opcTags = tags;
			initValveData();
			SetValveStatus();
            SetDeviceStatus();
        }

        /// <summary>
        /// Debug 在这里根据viewModel.ValveName进行取值显示操作
        /// </summary>
        private void initValveData()
        {
            // 随机生成阀门状态0：远程，1：本地手动，2：本地自动
            viewModel.ValveStatus = 1;
			// 随机生成设备状态0：关闭，1：开启，2：正在关闭，3：正在开启，4：故障
			int deviceStatus = 0;
			try
			{
				//先判断阀门状态是否正常
				foreach (OPCTag tag in opcTags)
				{
					string opcname = tag.OpcName;
					if (opcname.Contains("StatusFault"))
					{
						bool status = Convert.ToBoolean(tag.OpcValue.Value);
						if (status)
						{
							deviceStatus = 4;
							CommUtil.AddSystemLog(5, 3, opcname);
							break;
						}
					}
				}

				if(deviceStatus < 4)
				{
					foreach (OPCTag tag in opcTags)
					{
						string opcname = tag.OpcName;
						if (opcname.Contains("PV"))
						{
							current_pv = Convert.ToInt16(tag.OpcValue.Value);
							if (current_pv < 1)
							{
								deviceStatus = 0;
							}
							else if (current_pv > 99)
							{
								deviceStatus = 1;
							}
							else
							{
								deviceStatus = 3;
							}
							break;
						}
					}
				}
				viewModel.DeviceStatus = deviceStatus;
				// 随机百分比数值0%-100%
				viewModel.ValveValue = current_pv;
				set_pv = current_pv;
				OpenRatioTxt.Text = Convert.ToString(current_pv);
			}
			catch (Exception ex)
			{
				CommUtil.AddSystemLog(0, 2, ex.Message);
			}
        }

        /// <summary>
        /// 设置阀门状态
        /// 0：远程，1：本地手动，2：本地自动
        /// </summary>
        private void SetValveStatus()
        {
            vavleStatus0.Background = Get_Status_Color(false);
            vavleStatus1.Background = Get_Status_Color(false);
            vavleStatus2.Background = Get_Status_Color(false);
            if (viewModel.ValveStatus == 0)
            {
                vavleStatus0.Background = Get_Status_Color(true);
            }
            if (viewModel.ValveStatus == 1)
            {
                vavleStatus1.Background = Get_Status_Color(true);
            }
            if (viewModel.ValveStatus == 2)
            {
                vavleStatus2.Background = Get_Status_Color(true);
            }
        }

        /// <summary>
        /// 设置设备状态
        /// 0：关闭，1：开启，2：正在关闭，3：正在开启，4：故障
        /// </summary>
        private void SetDeviceStatus()
        {
            deviceStatus0.Background = Get_Status_Color(false);
            deviceStatus1.Background = Get_Status_Color(false);
            //deviceStatus2.Background = Get_Status_Color(false);
            deviceStatus3.Background = Get_Status_Color(false);
            deviceStatus4.Background = Get_Status_Color(false);
            if (viewModel.DeviceStatus == 0)
            {
                deviceStatus0.Background = Get_Status_Color(true);
            }
            if (viewModel.DeviceStatus == 1)
            {
                deviceStatus1.Background = Get_Status_Color(true);
            }
            //if (viewModel.DeviceStatus == 2)
            //{
            //    deviceStatus2.Background = Get_Status_Color(true);
            //}
            if (viewModel.DeviceStatus == 3)
            {
                deviceStatus3.Background = Get_Status_Color(true);
            }
            if (viewModel.DeviceStatus == 4)
            {
                deviceStatus4.Background = Get_Status_Color(true);
            }
        }

		private void OpenRatioTxt_LostFocus(object sender, RoutedEventArgs e)
		{
			try
			{
				set_pv = Convert.ToInt16(OpenRatioTxt.Text);
				if (set_pv > 100)
					set_pv = 100;
				else if (set_pv < 0)
					set_pv = 0;
				OpenRatioTxt.Text = Convert.ToString(set_pv);
			}
			catch(Exception ex) 
			{
				CommUtil.AddSystemLog(7, 20, ex.Message);
			}
		}

		/// <summary>
		/// 退出事件
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void ExitButton_Click(object sender, RoutedEventArgs e)
        {
            //返回false以阻止后续流程并退出 
            this.DialogResult = false;
        }


        /// <summary>
        /// 窗口拖动事件
        /// </summary>
        private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left)
            {
                DragMove();
            }
        }

        /// <summary>
        /// 阀门打开事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ValveOpen_Click(object sender, RoutedEventArgs e)
		{
			//当阀门pv时下发开启命令
			if (set_pv != current_pv && viewModel.DeviceStatus < 4)
			{
				foreach(OPCTag tag in opcTags)
				{
					string tagname = tag.OpcName;
					if(tagname.Contains("Setpoint"))
					{
						string cmd_tag1 = string.Format("{0}{1}", SysConfig.OPC_ADD_PRE, tagname);
						try
						{
							Close_Btn.Background = Get_Status_Color(false);
							App.UaClient.WriteNode<Int16>(cmd_tag1, Convert.ToInt16(set_pv));
						}
						catch (Exception ex)
						{
							CommUtil.AddSystemLog(0, 1, ex.Message);
						}
						return;
					}
				}
			}
		}

        /// <summary>
        /// 获取状态颜色
        /// </summary>
        /// <param name="status"></param>
        /// <returns></returns>
        private SolidColorBrush Get_Status_Color(bool status)
        {
            return status
                ? new SolidColorBrush((Color)ColorConverter.ConvertFromString("#50d000"))
                : new SolidColorBrush((Color)ColorConverter.ConvertFromString("#c6e0b6"));
        }
	}
}
